package com.example.byd

import android.content.Context
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import org.json.JSONObject

class RadarView(winmager: WindowManager,context: Context,radar:HashMap<String, String>): AppCompatActivity() {

    private var TAG="bydautosong"
    private var winmager_c:WindowManager?=null
    private var radar:HashMap<String, String>?=null
    private var context:Context?=null
//    private var radar_view:HashMap<String, TextView>?=null
    private var left_front_view:TextView?=null
    private var right_front_view:TextView?=null
    private var left_rear_view:TextView?=null
    private var right_rear_view:TextView?=null
    private var left_view:TextView?=null
    private var right_view:TextView?=null
    private var front_left_view:TextView?=null
    private var front_right_view:TextView?=null
    private var middle_rear_view:TextView?=null

    fun updatedata(radar:HashMap<String, String>){
        this.radar=radar
    }

    private fun creatlp(x: Int, y: Int, istouch: Boolean): WindowManager.LayoutParams {
        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            0,
            0,
            PixelFormat.TRANSPARENT
        )
        if(istouch){
            layoutParams.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH)
            }else{
            layoutParams.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    or WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW)
            }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE
        }

        layoutParams.format = PixelFormat.RGBA_8888
        layoutParams.gravity = Gravity.LEFT or Gravity.TOP
        layoutParams.x = x
        layoutParams.y = y
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
            layoutParams.type =WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
        }else{
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
            layoutParams.type =WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
        }else{
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }

    return layoutParams

    }

    init {
        winmager_c=winmager
        this.radar=radar
        this.context=context

    }

    private  fun addview(text:String,ptextview:TextView,x:Int,y:Int,color: Int,istouch:Boolean){
//        val text1 = TextView(this.context)
        ptextview.setText(text)
        ptextview.textSize = 30f
        ptextview.setTextColor(color)
//                    radar_view?.set("left_front", text1)

        val fangxiang=this.context?.resources?.configuration?.orientation
        Log.i(TAG,"当前的方向是${fangxiang}")

        val layoutParams = creatlp(x, y,istouch)
        if(istouch){
            ptextview.setOnTouchListener(FloatingOnTouchListener(layoutParams,winmager_c,this.context))
        }




        winmager_c!!.addView(ptextview, layoutParams)
    }

    private fun getposition(obj:JSONObject,key:String): Array<Int> {
        var x=10000
        var y=10000
        try {
            val postion = obj.getString(key)
            Log.d(TAG, "获取到坐标 ${postion}")
            val tempp=postion.split(",")




            x=tempp[0].toInt()
            y=tempp[1].toInt()

            Log.d(TAG, "获取到坐标11 x 是${x} y是${y} ")



        }catch (e:Exception){
            Log.d(TAG, "未获取到坐标")
        }

        return arrayOf(x,y)




    }

    fun addview(istouch: Boolean) {



        var postion: String

        for (ra in radar?.entries!!) {
            Log.d(TAG, "add view 1111 value is ${ra.value}");
            if (ra.value == "150") {
                continue
            }

            val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
            val value = sharedPreferences.getString("ra_position", "{}")
            Log.d(TAG, "value 111111 is ${value}");
            var obj:JSONObject
            try {
                 obj = value?.let { JSONObject(it) }!!
            }catch (e:Exception){
                 obj = JSONObject("{}")
            }

            val fangxiang=context?.resources?.configuration?.orientation
            when (ra.key) {
                "left_front" -> {
                    if(left_front_view==null){
                        left_front_view  = TextView(this.context)
                    }

                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    Log.d(TAG, "11111坐标 x 是${res[0]} y是${res[1]} ")
                    if(res[0]!=10000){
                        addview(ra.value, left_front_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, left_front_view!!,300,200,Color.rgb(255, 0, 0),istouch)
                    }

                }
                "right_front" -> {
                    if(right_front_view==null){
                        right_front_view  = TextView(this.context)
                    }

                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, right_front_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, right_front_view!!,300,300,Color.rgb(255, 0, 0),istouch)
                    }


                }
                "left_rear" -> {
                    if(left_rear_view==null){
                        left_rear_view  = TextView(this.context)
                    }
                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, left_rear_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, left_rear_view!!,300,400,Color.rgb(255, 0, 0),istouch)
                    }

                }
                "right_rear" -> {
                    if(right_rear_view==null){
                        right_rear_view  = TextView(this.context)
                    }
                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, right_rear_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, right_rear_view!!,300,500,Color.rgb(255, 0, 0),istouch)
                    }
                }
                "left" -> {
                    if(left_view==null){
                        left_view  = TextView(this.context)
                    }

                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, left_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, left_view!!,300,600,Color.rgb(255, 0, 0),istouch)
                    }

                }
                "right" -> {
                    if(right_view==null){
                        right_view  = TextView(this.context)
                    }

                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, right_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, right_view!!,300,700,Color.rgb(255, 0, 0),istouch)
                    }

                }
                "front_left" -> {
                    if(front_left_view==null){
                        front_left_view  = TextView(this.context)
                    }


                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, front_left_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, front_left_view!!,300,800,Color.rgb(255, 0, 0),istouch)
                    }


                }
                "front_right" -> {
                    if(front_right_view==null){
                        front_right_view  = TextView(this.context)
                    }

                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, front_right_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, front_right_view!!,300,900,Color.rgb(255, 0, 0),istouch)
                    }

                }
                "middle_rear" -> {
                    if(middle_rear_view==null){
                        middle_rear_view  = TextView(this.context)
                    }

                    val res=getposition(obj,"${ra.key}_${fangxiang}")
                    if(res[0]!=10000){
                        addview(ra.value, middle_rear_view!!,res[0],res[1],Color.rgb(255, 0, 0),istouch)
                    }else{
                        addview(ra.value, middle_rear_view!!,300,1000,Color.rgb(255, 0, 0),istouch)
                    }

                }
                else -> {
                    Log.i(TAG, "出问题了")
                }
            }


//        button.setOnTouchListener(FloatingOnTouchListener())
//        text1.setOnClickListener(object : View.OnClickListener {
//            override fun onClick(p1: View?) {
//                Toast.makeText(application, "我被点击了", Toast.LENGTH_SHORT).show()
//            }
//        })


        }
    }

    private fun safedelview(delview:TextView){
//        try {
            Log.i(TAG, "删除图层")
            if (delview != null) {
                if(delview.isShown){
                    winmager_c?.removeView(delview)
                }

            }
//        }catch (e:Exception){
//            Log.e("bydautosong","删除图层异常:"+System.err.toString())
//            Log.e("bydautosong", System.err.toString())
//        }
    }


    fun rmview(){

            Log.i(TAG, "删除图层")
              left_front_view?.let { safedelview(it) }
        right_front_view?.let { safedelview(it) }
        left_rear_view?.let { safedelview(it) }
        right_rear_view?.let { safedelview(it) }
        left_view?.let { safedelview(it) }
        right_view?.let { safedelview(it) }
        front_left_view?.let { safedelview(it) }
        front_right_view?.let { safedelview(it) }
        middle_rear_view?.let { safedelview(it) }




    }


        private class FloatingOnTouchListener(
            layoutParams: WindowManager.LayoutParams,
            winmager_c: WindowManager?,
            context: Context?
        ) : View.OnTouchListener, AppCompatActivity() {
        private var startX = 0
        private var startY = 0
        private var layoutParams: WindowManager.LayoutParams? =null
        private var winmager_c: WindowManager?=null
        private var TAG="bydautosong"
            private var context: Context?=null
       init {
                this.layoutParams=layoutParams
                this.winmager_c=winmager_c
                this.context=context

        }

        override fun onTouch(view: View, event: MotionEvent): Boolean {

            when (event.action) {


                MotionEvent.ACTION_DOWN -> {
                    startX = event.rawX.toInt()
                    startY = event.rawY.toInt()
                }
                MotionEvent.ACTION_MOVE -> {
                    val nowX = event.rawX.toInt()
                    val nowY = event.rawY.toInt()
                    val movedX = nowX - startX
                    val movedY = nowY - startY
                    startX = nowX
                    startY = nowY

                    if (layoutParams != null) {
                        layoutParams!!.x = layoutParams!!.x + movedX
                    }
                    if (layoutParams != null) {
                        layoutParams!!.y = layoutParams!!.y + movedY
                    }

                    // 更新悬浮窗控件布局
                    winmager_c?.updateViewLayout(view, layoutParams)
                }
                MotionEvent.ACTION_UP->{
                    val tview=view as TextView
                  val fangxiang=context?.resources?.configuration?.orientation
                    if(fangxiang == Configuration.ORIENTATION_LANDSCAPE){
                        Log.i(TAG,"现在是横屏")
                    }
                    if(fangxiang == Configuration.ORIENTATION_PORTRAIT){
                        Log.i(TAG,"现在是竖屏")
                        //---portrait mode---
                    }
                    val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
                    val edit=sharedPreferences.edit()
                    val value = sharedPreferences.getString("ra_position", "{}")

                    Log.i(TAG,"现在的坐标信息是${value}")

                    var obj:JSONObject
                    try {
                        obj = value?.let { JSONObject(it) }!!
                    }catch (e:Exception){
                        obj=JSONObject("{}")
                    }



                    val nowX = event.rawX.toInt()-90
                    val nowY = event.rawY.toInt()-150
                    when(tview.text){
                        "左前" -> {
                            obj.put("left_front_${fangxiang}","${nowX},${nowY}")
                        }
                        "右前" -> {
                            obj.put("right_front_${fangxiang}","${nowX},${nowY}")
                        }
                        "左后" -> {
                            obj.put("left_rear_${fangxiang}","${nowX},${nowY}")
                        }
                        "右后" -> {
                            obj.put("right_rear_${fangxiang}","${nowX},${nowY}")
                        }
                        "左侧" -> {
                            obj.put("left_${fangxiang}","${nowX},${nowY}")
                        }
                        "右侧" -> {
                            obj.put("right_${fangxiang}","${nowX},${nowY}")
                        }
                        "左前1" -> {
                            obj.put("front_left_${fangxiang}","${nowX},${nowY}")
                        }
                        "右前1" -> {
                            obj.put("front_right_${fangxiang}","${nowX},${nowY}")
                        }
                        "后侧" -> {
                            obj.put("middle_rear_${fangxiang}","${nowX},${nowY}")
                        }
                    }

                    edit.putString("ra_position",obj.toString())
                    edit.commit()



                    Log.i(TAG,"${tview.text}最终的位置是${nowX},${nowY}")



                    Log.i(TAG,"更新后的信息是${obj.toString()}")
                }
                else -> {}
            }
            return false
        }
    }




}